<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        div{
            width: 200px;
            height: 200px;
            background-color: red;
            position: absolute;
        }
    </style>
</head>
<body>

    <div>

    </div>
    <script>
        var div=document.querySelector("div")
        div.onmousedown=function(e)   //鼠标按下事件
        {
            var offsetX=e.clientX-div.offsetLeft;  //鼠标按下的时候计算
            var offsetY=e.clientY-div.offsetTop;
            console.log(div.offsetLeft);
            console.log(div.offsetTop);
            document.onmousemove=function(ev)    //鼠标移动事件
            {
                var x=ev.clientX-offsetX;   //鼠标移动时候的计算
                var y=ev.clientY-offsetY;
            
                if(x<0) x=0   //盒子移动不能超过浏览器
                var maxX=document.documentElement.clientWidth-div.offsetWidth
                if(x>maxX) x=maxX
                if(y<0) y=0
                var maxY=document.documentElement.clientHeight-div.offsetHeight
                if(y>maxY) y=maxY

                div.style.left=x+'px'  //赋值
                div.style.top=y+'px'
            }
        }
        div.onmouseup=function()   //鼠标松开事件
        {
            document.onmousemove=null;
        }
    </script>
    
</body>
</html>